#include "accountmember.h"
#include <network/networkmanager.h>
#include <network/networkhttprequest.h>
#include <network/networkresponse.h>
#include "accountgetavatarrequest.h"
#include <network/image/imagegetimageresponse.h>

// Qt includes
#include <QPixmap>
#include <QDebug>


using namespace Account;

Member::Member(QObject *parent) :
    QObject(parent),
    m_onlineStatus(false)
{
}

Member::Member(int id,
               const QString &userName,
               const QString &displayName,
               const QString &avatar,
               QObject *parent) :
    QObject(parent),
    m_id(id),
    m_userName(userName),
    m_displayName(displayName),
    m_avatar(avatar),
    m_onlineStatus(false)
{
}

bool Member::operator < (const Member &another) const
{
    return (m_displayName < another.m_displayName);
}

bool Member::compare(const Member *first, const Member *second)
{
    if ((first != NULL) && (second != NULL)) {
        return (*first < *second);
    }

    return true;
}

void Member::setInfo(int id,
                     const QString &userName,
                     const QString &displayName,
                     const QString &avatar)
{
    m_id = id;
    m_userName = userName;
    m_displayName = displayName;
    m_avatar = avatar;
    emit dataChanged(this);
}

void Member::requestData()
{
    postGetAvatarRequest();

}

void Member::postGetAvatarRequest()
{
    if (m_avatar.isNull() || m_avatar.isEmpty())
        return;

    GetAvatarRequest *avatarRequest = new GetAvatarRequest(this, this);
    connect(avatarRequest, &GetAvatarRequest::responded,
            this, &Member::onGetAvatarResponsed);

    Network::Manager *manager = Network::Manager::instance();
    if (!manager->post(avatarRequest)) {
        delete avatarRequest;
        avatarRequest = NULL;
        return;
    }
}


void Member::setOnlineStatus(bool status)
{
    m_onlineStatus = status;
}

const QPixmap &Member::pixmap() const
{
    return m_avatarPixmap;
}

void Member::onGetAvatarResponsed(Network::HttpRequest *request)
{
    const Network::HttpRequest &constRequest = *request;
    const Network::Response &response = constRequest.response();
    if (response.type() != Network::Response::GetImage)
        return;

    const Network::GetImageResponse &avatarResponse = (const Network::GetImageResponse &)response;
    QPixmap *pixmap = avatarResponse.pixmap();
    if (!pixmap)
        return;
    if (pixmap->isNull())
        return;
    m_avatarPixmap = QPixmap(*pixmap);
    emit avatarReady(this);

    request->deleteLater();
}

